import React, { Component,useState,useEffect,createContext,useContext, useReducer} from 'react';
// useContext解决原生类组件传值的方式，与useReducer配合形成redux的操作，状态全局化
const CountContext=createContext()
function Example4(){
    const[count,setCount]=useState(0)
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={()=>{setCount(count+1)}}>click me</button> 
               {/*父组件传值给子组件  */}
            <CountContext.Provider value={count}><Counter /></CountContext.Provider>
        </div>
    )
}
function Counter(){
    const count = useContext(CountContext)  //一句话就可以得到count
    return (<h2>{count}</h2>)
  }

  function ReducerDemo(){
    //   useReducer传参第一个函数，第二个默认值，返回一个数组第一个是改变后状态值，是一个传值的函数
    const [ count , dispatch ] =useReducer((state,action)=>{
        switch(action){
            case 'add':
                return state+1
            case 'sub':
                return state-1
            default:
                return state
        }
    },0)

    return (
        <div>
            <h2>现在的分数是{count}</h2>
            <button onClick={()=>dispatch('add')}>Increment</button>
            <button onClick={()=>dispatch('sub')}>Decrement</button>
        </div>
     )
  }
export default ReducerDemo;